package com.jlnk.androidfmc.adapter;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.jlnk.androidfmc.R;
import com.jlnk.androidfmc.entity.News;

import java.util.List;

public class NewsAdapter extends BaseAdapter {
    private Context context;
    private List<News> newsList;
    private LayoutInflater inflater;

    public NewsAdapter(Context context, List<News> newsList) {
        this.context = context;
        this.newsList = newsList;
        this.inflater = LayoutInflater.from(context);
    }

    public void clear() {
        newsList.clear();
    }

    public void addAll(List<News> newsList) {
        this.newsList.addAll(newsList);
    }

    @Override
    public int getCount() {
        return newsList.size();
    }

    @Override
    public Object getItem(int position) {
        return newsList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if (convertView == null) {
            convertView = inflater.inflate(R.layout.news_item, parent, false);
            holder = new ViewHolder();
            holder.newsImage = convertView.findViewById(R.id.news_image);
            holder.newsTitle = convertView.findViewById(R.id.news_title);
            holder.newsContent = convertView.findViewById(R.id.news_content);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        News news = newsList.get(position);
        holder.newsTitle.setText(news.getTitle());
        holder.newsContent.setText(news.getContent());

        // 使用 News 实体的 getImage() 方法来获取 Bitmap 对象并设置到 ImageView
        Bitmap bitmap = news.getImage();
        if (bitmap != null) {
            holder.newsImage.setImageBitmap(bitmap);
        } else {
            // 如果 bitmap 为 null，设置一个默认图片
            holder.newsImage.setImageResource(R.drawable.n1); // 替换 your_default_image 为实际的默认图片资源
        }

        return convertView;
    }

    private static class ViewHolder {
        ImageView newsImage;
        TextView newsTitle;
        TextView newsContent;
    }
    public void updateList(List<News> newsList) {
        this.newsList.clear();
        this.newsList.addAll(newsList);
        notifyDataSetChanged();
    }
    public void addNews(News news) {
        newsList.add(0, news); // 将新新闻添加到列表顶部
        notifyDataSetChanged(); // 通知数据已更改
    }



}